(function(helloWorld, undefined){
	(function(mv){
		mv.movieList = [];
				
		// ======== client event or html
		mv.init = function(){
			mv.clearBasket();
			
			$('#btn_new_movie').click(mv.getServerList);
			$('#btn_insert_movie').click(function(){
				// put the only single movie to an array
				mv.postMovie([JSON.stringify(mv.getClientData())]);
			});
			$('#btn_insert_movie_list').click(function(){
				mv.postMovie(JSON.stringify(mv.movieList));
			});
			$('#btn_basket_movie').click(mv.basketMovie);
		};
		
		mv.clearClientData = function(movieAreaId){
			movieAreaId = movieAreaId || 'div_movie_details_area';
			$('#'+movieAreaId+ ' input:text').each(function(){
				$(this).val('');
			});
		};
		
		mv.clearBasket = function(){
			mv.movieList = [];
			$('#span_current_mv_number').text(mv.movieList.length);
		};
		
		mv.getClientData = function(movieAreaId){
			movieAreaId = movieAreaId || 'div_movie_details_area';
			var m = {};
			$('#'+movieAreaId+ ' input:text').each(function(){
				m[$.trim($(this).attr('id'))] = $.trim($(this).val());
			});
			
			return m;
		};
		
		mv.basketMovie = function(){
			mv.movieList.push(mv.getClientData());
			mv.clearClientData();
			$('#span_current_mv_number').text(mv.movieList.length);
			// start input from movie id
			document.getElementById('ipt_movie_id').focus();
		};
		
		// ======== communication with server
		mv.getServerList = function(){
			$.getJSON("/HelloWorld/RefreshMovie",
          	{},
          	function(data){
            	  console.log(data);
          	});
		};
		
		mv.postMovie = function(movies){
			$.ajax({
				url: 'HelloWorld/InsertMovie/',
				data: {'movies': movies},
				// contentType: 'application/json; charset=utf-8',
				type: 'POST',
				success: function(data){
					if (data && data['error'] && data['error'].length){
						alert(data['error']);
					} else {
						alert(data['success'] || 'success');
						mv.clearBasket();
					}
				}
			});
		};
	}(helloWorld.movie = helloWorld.movie || {}));
}(helloWorld = window.helloWorld || {}));
